﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.IO;

namespace TestGame
{
    public class Map
    {
        Tile[] map;
        public int width { private set; get; }
        public int height { private set; get; }
        public string title { private set; get; }
        public int tileWidth { private set; get; }
        public int tileHeight { private set; get; }
        public int totalHeight { private set; get; }
        public int totalWidth { private set; get; }

        public Map(MapProto mp)
        {
            SetBounds(mp);
            CreateTiles(mp);
        }

        // TODO: reset tiles on map change
        private void SetBounds(MapProto mp)
        {
            width = mp.width;
            height = mp.height;
            tileWidth = Game.TILE_WIDTH;
            tileHeight = Game.TILE_HEIGHT;
            title = mp.author;
            totalHeight = height * tileHeight;
            totalWidth = width * tileWidth;
        }

        public void unloadMap()
        {
            foreach (Tile t in map)
            {
                //SpriteManager.sprites.Remove(t);
            }
        }

        private void CreateTiles(MapProto mp)
        {
            //parse the map file
            map = new Tile[width * height];
            string[] tiles = mp.Map.Split(',');

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    // get each of the individual tiles and add them to the map
                    String path = @"tiles\" + tiles[(y * width) + x].Trim();
                    if (!TileMapManager.tiles.ContainsKey(path))
                    {
                        path += "null";
                    }

                    // create an instance of the tile
                    Tile newTile = new Tile(x * tileWidth, y * tileHeight, TileMapManager.tiles[path]);
                    map[(y * width) + x] = newTile;
                }
            }
        }
    }
}